//
//  MusicHistoryViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/25.
//

import UIKit
import SVProgressHUD

class MusicHistoryViewController: BaseViewController {
    var viewModel = MusicViewModel()
    var dataSource:[MusicModel] = []
    var disposeBag = DisposeBag()
    var name:String = ""
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: MusicHistoryCell.self)
        view.rowHeight = UITableView.automaticDimension
        view.sectionHeaderHeight = 0
        view.estimatedSectionHeaderHeight = 0
        view.sectionFooterHeight = 0
        view.estimatedSectionFooterHeight = 0
        view.contentInsetAdjustmentBehavior = .never
        view.separatorStyle = .none
        view.emptyDataSetSource = self
        view.emptyDataSetDelegate = self
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "我的音乐"
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        
        let rightBtn = UIButton(type: .custom)
        rightBtn.setTitle("定制音乐", for: .normal)
        rightBtn.normalTitleColor = .white
        rightBtn.allRound(12)
        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 14)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            self?.navigationController?.popToRootViewController(animated: true)
        }
        
        self.tableView.addHeaderRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page = 1
            self.tableView.reloadData()
            self.viewModel.userList()
        }
        
        self.tableView.addFooterRefresh { [weak self] in
            guard let self = self else { return }
            self.viewModel.page += 1
            self.viewModel.userList()
        }
        
        self.viewModel.userList()
        
        self.viewModel.reloadUserListDataSubject.subscribe(onNext: { [weak self] models in
            guard let self = self else { return }
            self.tableView.endFooterRefresh()
            self.tableView.endHeaderRefresh()
            if self.viewModel.page == 1 {
                self.dataSource = models
            }else {
                self.dataSource += models
            }
            self.tableView.reloadData()
        }).disposed(by: disposeBag)
     }
    
 
    func clickMore(model:MusicModel) {
        // 创建 UIAlertController 并指定为 action sheet 样式
          let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
          // 添加"分享"按钮
          let shareAction = UIAlertAction(title: "分享", style: .default) { _ in
              // 处理分享的逻辑
              self.shareLinkWithCover(urlString: model.share_page ?? "")
          }
          actionSheet.addAction(shareAction)
          
          // 添加"删除"按钮
          let deleteAction = UIAlertAction(title: "删除", style: .destructive) { _ in
              // 处理删除的逻辑
              print("删除按钮被点击")
              self.viewModel.deleteMusic(id: "\(model.id ?? 0)")
          }
          actionSheet.addAction(deleteAction)
          
//          // 添加"下载"按钮
//          let downloadAction = UIAlertAction(title: "下载", style: .default) { _ in
//              // 处理下载的逻辑
//              print("下载按钮被点击")
//              self.startDownload(model.music_url ?? "", name: model.music_name ?? "")
//          }
//          actionSheet.addAction(downloadAction)
          
          // 添加"取消"按钮
          let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
              // 处理取消的逻辑
              print("取消按钮被点击")
               
          }
          actionSheet.addAction(cancelAction)
          
          // 显示弹窗
          self.present(actionSheet, animated: true, completion: nil)
    }
    
    func shareLinkWithCover(urlString: String) {
        guard let url = URL(string: urlString) else { return }

        // 创建一个包含链接和封面图片的数组
        let itemsToShare: [Any] = [url]
        
        // 创建分享活动视图控制器
        let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
        
        // 排除某些活动类型（根据需要）
        activityViewController.excludedActivityTypes = [
            .assignToContact,
            .saveToCameraRoll,
            .addToReadingList,
            .postToVimeo
        ]
        
        // 显示分享界面
        self.present(activityViewController, animated: true, completion: nil)
    }
}

extension MusicHistoryViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    // sts 状态：1生成中；2生成成功；3生成失败

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.dataSource[indexPath.item]
        let cell = tableView.dequeueReusableCell(withClass: MusicHistoryCell.self)
        cell.setup(model: model)
        cell.moreBtn.setClosureTouchUpInside_k { [weak self] in
            self?.clickMore(model: model)
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.item]
        if model.sts == 2 {
            let vc = MusicPlayerDetailsViewController()
            vc.model = model
            self.navigationController?.pushViewController(vc)
        }
    }
 
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
           // 创建自定义的删除动作
           let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { [weak self] (action, view, completionHandler) in
               guard let self = self else { return }
               let model = self.dataSource[indexPath.item]
               self.viewModel.deleteMusic(id: "\(model.id ?? 0)")
               // 删除数据源中的项目
//               self.dataSource.remove(at: indexPath.row)
//                更新 tableView
//               tableView.deleteRows(at: [indexPath], with: .automatic)
               // 完成处理
               completionHandler(true)
           }
           // 设置自定义图标
           deleteAction.image = UIImage(named: "icon_music_delete")
           deleteAction.backgroundColor = .red // 背景色
           // 创建配置
           let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
           configuration.performsFirstActionWithFullSwipe = true
           return configuration
       }
}
extension MusicHistoryViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
    open func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        UIImage(named: "icon_nodata")
    }
    
    open func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "暂无数据，快去生成吧～"
        let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.pingFangSCRegular(ofSize: 15), .foregroundColor: Theme.color.text_d3]
        return NSAttributedString(string: text, attributes: attributes)
    }
   
}
extension MusicHistoryViewController: URLSessionDownloadDelegate{
    // 下载 MP3 文件到本地
      func downloadMP3(from url: URL, to destinationURL: URL) {
          // 配置 URLSession
          let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
          
          // 创建下载任务
          let downloadTask = session.downloadTask(with: url)
          
          // 启动下载任务
          downloadTask.resume()
      }
      
      // 按钮点击事件触发下载
    func startDownload(_ urlString: String, name:String) {
          guard let url = URL(string: urlString) else { return }
          let fileManager = FileManager.default
          let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
          let destinationURL = documentsDirectory.appendingPathComponent("\(name).mp3")
            self.name = name
        
          downloadMP3(from: url, to: destinationURL)
      }
    // 处理下载进度
     func urlSession(_ session: URLSession, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
         let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
         SVProgressHUD.showProgress(progress, status: "下载中...")
     }
     
     // 处理下载完成
     func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
         // 获取下载完成的文件 URL
         let fileManager = FileManager.default
         let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
         let destinationURL = documentsDirectory.appendingPathComponent("\(self.name).mp3")
         do {
             // 移动文件到目标位置
             try fileManager.moveItem(at: location, to: destinationURL)
             self.saveFileToiCloud()
             NDProgressHUD.showSuccess(title: "", subtitle: "下载完成")
         } catch {
             NDProgressHUD.showError(title: "", subtitle: "下载错误:\(error.localizedDescription)")
         }
     }
     
     // 处理下载失败
     func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
         if let error = error {
             NDProgressHUD.showError(title: "", subtitle: "下载错误:\(error.localizedDescription)")
         }
     }
    
    func saveFileToiCloud() {
        let fileManager = FileManager.default
        let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let destinationURL = documentsDirectory.appendingPathComponent("\(self.name).mp3")
            // 获取 iCloud Drive 的文件目录
            let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
            
            do {
                // 将文件移动到 iCloud Drive 目录
                if let iCloudDocumentsURL = iCloudDocumentsURL {
                    try FileManager.default.moveItem(at: destinationURL, to: iCloudDocumentsURL.appendingPathComponent("downloaded_audio.mp3"))
                }
            } catch {
                print("Error moving file to iCloud: \(error.localizedDescription)")
            }
        }
    
}
